package org.groupg.practice;

import org.jctools.queues.SpscArrayQueue;

/**
 * 胆生产者单消费者
 */
public class SpscExample {
    // 创建一个有界SPSC队列，容量为1024
    private static final SpscArrayQueue<Integer> queue = new SpscArrayQueue<>(1024);

    public static void main(String[] args) throws InterruptedException {
        // 生产者线程
        Thread producer = new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                // 尝试添加元素，如果队列满则返回false
                while (!queue.offer(i)) {
                    // 队列满时，可稍后重试或处理
                    Thread.yield();
                }
            }
            System.out.println("Producer finished");
        });

        // 消费者线程
        Thread consumer = new Thread(() -> {
            int received = 0;
            while (received < 1000) {
                Integer element = queue.poll();
                if (element != null) {
                    received++;
                    // 处理元素
                    System.out.println("Consumed: " + element);
                } else {
                    // 队列空时，可稍后重试
                    Thread.yield();
                }
            }
            System.out.println("Consumer finished");
        });

        producer.start();
        consumer.start();
        producer.join();
        consumer.join();
        System.out.println("Final queue size: " + queue.size());
    }
}